package com.sunkyc.framework.utils;

import cn.hutool.core.util.ObjectUtil;
import com.sunkyc.commons.annotation.DataScope;

import java.lang.reflect.Method;

public class DataScopeUtil {

    /**
     * 根据执行方法获取当前执行的接口或者类的Class对象
     */
    public static Class<?> getCurrentClass(Method method) {
        return method.getDeclaringClass();
    }

    /**
     * 根据方法路径(包全路径+方法名称)获取类
     *
     * @param methodPath
     * @return
     * @throws ClassNotFoundException
     */
    public static Class<?> getCurrentClass(String methodPath) throws ClassNotFoundException {
        Class<?> clazz = Class.forName(methodPath.substring(0, methodPath.lastIndexOf(".")));
        return clazz;
    }


    /**
     * 根据方法路径(包全路径+方法名称)获取方法名称
     *
     * @param methodPath
     * @return
     */
    public static String getMethodName(String methodPath) {
        String methodName = methodPath.substring(methodPath.lastIndexOf(".") + 1);
        return methodName;
    }

    /**
     * 获取指定class内的方法对象
     *
     * @param clazz
     * @param methodName
     * @return
     */
    public static Method getMethod(Class<?> clazz, String methodName) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }

    /**
     * 校验mapper或者mapper中执行的方法上是否有数据权限注解
     * @param methodPath
     * @return
     * @throws ClassNotFoundException
     */
    public static Boolean checkedIsAnntion(String methodPath) throws ClassNotFoundException {
        Class<?> currentClass = getCurrentClass(methodPath);
        DataScope classAnnotation = currentClass.getAnnotation(DataScope.class);
        // 获取方法--->获取方法上的注解
        Method method = getMethod(currentClass, DataScopeUtil.getMethodName(methodPath));
        DataScope methodAnnotation = null;
        if (ObjectUtil.isNotNull(method)) {
            methodAnnotation = method.getAnnotation(DataScope.class);
        }
        return ObjectUtil.isNotNull(classAnnotation) || ObjectUtil.isNotNull(methodAnnotation);
    }


}
